How to get the string's byte length?

I have some string,I want to get the string's byte length,how
can do it?
for example:
<cfoutput>#len('hihi,这是测试')#</cfoutput>
output is 9
I want to get the byte length is 14, how can i get it?
Thanks.

>> Fair cop. I didn't realise that asc() returned the
codepoint rather than the
> actual character code.
>
> and what would be the difference?
Oh, sorry, whatever the term is (I'm crap with jargon). The
value returned
by asc() for those chars was only two bytes (ie: four hex
digits). I
didn't realise there was more to it than that, and that
2-byte value maps
to some other THREE byte value. I need to do some reading...
> that's what both cf & java counted as the length.
CHARACTER length, sure. No-one's disputing that. On the other
hand,
no-one's asking about it, either.
> by adding a BOM you've already effected the encoding,
which may or may not
> match the original. so you still don't know how many
bytes were in the original
> string.
[groan]
Yes, that's a reasonable strawman there. I was only putting
it in a file
so I could save it and check the number of bytes occupied by
the data.
Clearly... CLEARLY... the OP is not asking for a character
length of that
string. They've said as much.
I copy and pasted the string from their post, and used it as
a
demonstration of how "nine" is not the right answer for the
BYTE LENGTH of
that string. Whether or not the original string was UTF-8,
UTF-16 or
special-marmoset-encoding, it almost certainly was NOT in a
fictitious kind
encoding in which each of those particular characters only
occupied one
byte each, which would mean that "nine" is the correct answer
to the
question.
When I copied those characters from either the web browser
for from my
text-based news agent, notepad identified them (and rendered
them
correctly) as UTF-8, so I'm fairly confident they ARE UTF-8.
Of course
this could be down to some intermediary encoding (pasting
them in to the
original posting, for example, via some encoding-transforming
mechanism),
but Occam's Razor suggests the original question was from a
UTF-8 POV.
But maybe we should quit speculating and ask the OP. Unless
they've
buggered off in despair of how drawn out all this is getting.
For which I
would not blame them.
Adam

Similar Messages

  • How to get the number of bytes at TCP port

    Hi all,
    How to get the number of bytes to read at the TCp port...as someone had suggested in some forum we do read the number of bytes first and then pass this...
    but we get a problem when we have FF data in this...because then it sends 2 FF data...and cause of this we skip the last data...is there any solution for the same?

    Hi
    In LabVIEW you don't have the same property as in serail port.
    You havn't "Byte at TCPIP port".
    if you developp a protocol, one soltion, is to send the size to read.
    Ingénieur d'Application / Développeur LabVIEW Certifié (CLD)
    Application Engineer / LabVIEW Certified Developer (CLD)

  • How to get the number of bytes stored in a field?

    Hi Guys,
    How can i get the number of bytes stored in a field.
    I tried using DESCRIBE FIELD, But here i am getting the length from the definition.
    i.e 8 bytes for string and for character value is from definition.
    Prompt replies will be Awarded with full points:-)
    Thanks,
    vinod.

    u see this : http://help.sap.com/saphelp_nw04/helpdata/en/cf/21f2e5446011d189700000e8322d00/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/cf/21f2e5446011d189700000e8322d00/frameset.htm
    Madhavi

  • How to get a string or byte array representation of an Image/BufferedImage?

    I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
    To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
    private void send(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        try {
            BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            ImageIcon imageIcon = new ImageIcon(image);
            ImageObserver observer = imageIcon.getImageObserver();
            buffImage.getGraphics().setColor(new Color(255, 255, 255));
            buffImage.getGraphics().fillRect(0, 0, width, height);
            buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
            jpeg.encode(buffImage);
            URL url = new URL(/* my url... */);
            URLConnection connection = url.openConnection();
            String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("method", "POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            String output = "--" + boundary + "\r\n"
                          + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                          + "Content-Type: image/jpeg\r\n"
                          + "Content-Transfer-Encoding: base64\r\n\r\n"
                          + new String(stream.toByteArray())
                          + "\r\n--" + boundary + "--\r\n";
            connection.setDoOutput(true);
            connection.getOutputStream().write(output.getBytes());
            connection.connect();
        } catch {
    }This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
    Maybe I should say that I can display the original Image object on screen correctly.
    I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
    Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

    Here you go:
      private static void send(BufferedImage image) throws Exception
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", byteArrayOutputStream);
        byte[] imageByteArray = byteArrayOutputStream.toByteArray();
        URL url = new URL("http://<host>:<port>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        outputStream.close();
        connection.connect();
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();
      }

  • How to get the string value from the RichSelectBooleanCheckBox component?

    I added a validator to a RichSelectBooleanCheckBox component which is binded to a String attribute of a View Object.
    I defined the mapping of boolean value to corresponding String value in the corresponding attribute binding in the page definition.
    When the validate() method of my validator was invoked, the new value passed to the validate method() was a Boolean value instead of the converted String value.
    I need to write validate() method generically so that it can handle more than one way of mapping boolean values to String values.
    How can I get the converted String value in my validator method() from the RichBooleanCheckBox component that was also passed to the validate() method as a parameter?

    use:
    int num = Integer.parseInt(s);

  • How to get a string with fixed length

    I want to implement something like movechar() of c in java. I want to return a string which has a fixed length that contains the given string and spaces for remaining length.
    Please let me know how can I implement it.
    Thanks & Regards,
    Nasrin.n

    Do you mean padding a String?
          * This method pads the string s to size n using char c to make up for missing characters.
         public static String padString(String s, int n, char c, boolean paddingLeft) {
              StringBuffer str = new StringBuffer(s);
              int strLength = str.length();
              if (n > 0 && n > strLength) {
                   for (int i = 0; i <= n; i++) {
                        if (paddingLeft) {
                             if (i < n - strLength) str.insert(0, c);
                        else {
                             if (i > strLength) str.append(c);
              return str.toString();
         }

  • How to get the number of bytes at ethernt port using tcp/ip?

    I have data with variable sizes.I am getting the data from another sytem using software C.
    How can I get the exact number of bytes coming at the port before using the read command so that the no. of bytes at port has to be given as the input to the tcp read vi?

    Philippe_RSA wrote:
    So may responses saying your question is wrong..... typical of this site, and no decent answer after 5 years !
    The answer I have used is to use a call library function:
    short int ioctlsocket(unsigned long socket, unsigned long fionread, unsigned long *len);    
    where fionread is a windows defined constant =  4004667F
    The socket can be obtained from using the       TCP Get RAW NET OBJECT.vi   which comes with Labview (even as far back as version 7).
    Good luck.
    A protocol requiring such a hack is IMHO very poorly designed. You should always have some way on the wire to determine the data stream size. If the data is fixed size that would be inherent to the protocol, if it's variable sized there should be a fixed size header or a known message termination indication that can be used to determine how to read the rest of the message.
    As a side node, I do consider the existence of VISA Bytes at Serial Port a big error, and that is most likely where this question originally came from. Use of "bytes at port" to decode a protocol will ALWAYS lead to protocol errors sooner or later, and code that is unneccessarily complicated to force the routine to deal with the asynchonous reading of the "bytes at port" into the protocol decoding.
    If a protocol can't be decoded with fixed size reads, fixed size reads with following variable size reads determined from information in the header, or a specific message termination indication, then it is very badly flawed.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Get the string until first space

    hi,
    can anyone provide an example how to get the string until the first space?
    i mean if the value is :
    this is an example
    how to get only the word "this" (before the very first space) by select?
    thanks in advance,

    There are several methods to achieve this:
    SELECT SUBSTR(t.col1, 1, INSTR(t.col1 || ' ', ' ') - 1)
      FROM (SELECT 'this is an example' col1
              FROM dual) t
         ;     or in 10g using regular expressions:
    SELECT REGEXP_SUBSTR(t.col1, '^[^ ]+')
      FROM (SELECT 'this is an example' col1
              FROM dual) t
         ;     C.

  • How to get the file size (in bytes) for all files in a directory?

    How to get the file size (in bytes) for all files in a directory?
    The following code does not work. isFile() does NOT recognize files as files but only as directories. Why?
    Furthermore the size is not retrieved correctly.
    How do I have to code it otherwise? Is there a way of not converting f-to-string-to-File again but iterate over all file objects instead?
    Thank you
    Peter
    java.io.File f = new java.io.File("D:/todo/");
    files = f.list();
    for (int i = 0; i < files.length; i++) {
    System.out.println("fn=" + files);
    if (new File(files[i]).isFile())
         System.out.println("file[" + i + "]=" + files[i] + " size=" + (new File(files[i])).length() ); }

    pstein wrote:
    ...The following code does not work. Work?! It does not even compile! Please consider posting code in the form of an SSCCE in future.
    Here is an SSCCE.
    import java.io.File;
    class ListFiles {
        public static void main(String[] args) {
            java.io.File f = new java.io.File("/media/disk");
            // provides only the file names, not the path/name!
            //String[] files = f.list();
            File[] files = f.listFiles();
            for (int i = 0; i < files.length; i++) {
                System.out.println("fn=" + files);
    if (files[i].isFile()) {
    System.out.println(
    "file[" +
    i +
    "]=" +
    files[i] +
    " size=" +
    (files[i]).length() );
    }Edit 1:
    Also, in future, when posting code, code snippets, HTML/XML or input/output, please use the code tags to retain the indentation and formatting.   To do that, select the code and click the CODE button seen on the Plain Text tab of the message posting form.  It took me longer to clean up that code and turn it into an SSCCE, than it took to +solve the problem.+
    Edited by: AndrewThompson64 on Jul 21, 2009 8:47 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to get the viewrow value by string

    Using Jdev11.1.1.5.0-adfbc-ireport3.0.0
    here i'll describe: what i did.
    am using jsff(dynamic region) while hitting the af:tree nodes it will opens. ok fine
    i had somevo with manually wroten query. and query is fine no problem with that
    here i give sample not a original query
    select * from sometable where acctid = :pacctidi drag and drop the pacctid from corresponding execute params vo as selectoncechoice
    static vo
    Data value - account payable , advance
    Data Name - ap,ad
    in that jsff
    *page representation*
    account type :   account payable (ap) - select one choice type
                            advance           (ad) - select one choice type
    like this some select once choice and some inputs.
    Run report - command button
    .jsff code
    <af:selectOneChoice value="#{bindings.ACCT_TYPE.inputValue}"
                              label="Account Type"
                              shortDesc="#{bindings.ACCT_TYPE.hints.tooltip}"
                              id="soc3" required="true"
                              autoSubmit="true"
                              binding="#{backingBeanScope.SUP1040V.soc3}"
                              valuePassThru="true"
                              valueChangeListener="#{backingBeanScope.SUP1040V.ValueChangeListener1}">
            <f:selectItems value="#{bindings.ACCT_TYPE.items}" id="si3"/>
          </af:selectOneChoice>
    <af:commandToolbarButton text="Export in pdf" id="ctb2">
              <af:fileDownloadActionListener method="#{backingBeanScope.SUP1040V.Report}"
                                             />
            </af:commandToolbarButton>.java
         //while hitting the button following logs are appeared i show it as commented format.
        public void Report(FacesContext context, OutputStream out) throws IOException,Exception
                FacesContext ctx = FacesContext.getCurrentInstance();
                HttpServletRequest request =
                    (HttpServletRequest)ctx.getExternalContext().getRequest();
                HttpServletResponse response = 
                    (HttpServletResponse)ctx.getExternalContext().getResponse();
                BindingContainer bindings1 = BindingContext.getCurrent().getCurrentBindingsEntry();
                System.out.println("print binding" +bindings1 );
    //while using sop i get this in my log : :  print binding  ReportsPageFragments_SUP1040VPageDef_WEB_INF_TaskFlows_SUP1040_V_TF_xml_SUP1040_V_TF
                JUCtrlListBinding listBinding1 = (JUCtrlListBinding)bindings1.get("ACCT_TYPE");
                System.out.println("print list bindings" +listBinding1 );
    //while using sop i get this in my log : :  print list  bindings0
                Object selectedValue1 = listBinding1.getSelectedValue();
                System.out.println("print selected value" + selectedValue1);
    //while using sop i get this in my log : :  print selected  valueViewRow [oracle.jbo.Key[AP ]]   
    request.setAttribute("ACCT_TYPE", //here i want the value  "AP" in  String  );
    if i use like this means
    request.setAttribute("ACCT_TYPE", soc1.getValue()  );  i get the index value.
    i need the dataname "ap" so i go above method which say wrotes ...
                request.getRequestDispatcher(response.encodeURL("/sup1040servlet")).forward(request,response);
                System.out.println("hihihihih");
                response.flushBuffer();
                ctx.responseComplete();
        public void ValueChangeListener1(ValueChangeEvent valueChangeEvent) {
            // Add event code here...
            String AcctType = valueChangeEvent.getNewValue().toString();
            System.out.println("AcctType" + AcctType);
            FacesContext contxt = FacesContext.getCurrentInstance();
            valueChangeEvent.getComponent().processUpdates(contxt);
           BindingContainer bindings1 =
           BindingContext.getCurrent().getCurrentBindingsEntry();
           // Get the sepecific list binding
           JUCtrlListBinding listBinding1 =
           (JUCtrlListBinding)bindings1.get("ACCT_TYPE");
           // Get the value which is currently selected
           Object selectedValue1 = listBinding1.getSelectedValue();
           System.out.println(selectedValue1);
        }if i get ap means my report runs. or else it will shows empty page.
    how to get the viewrowimpl class value as string.
    Edited by: ADF7 on Mar 24, 2012 7:27 AM

    ADF7,
    I'm not sure I understand what you are up to.
    As far as I understand you want to get the display value instead of the index
    I use this code
        public void StatusChangedListener(ValueChangeEvent valueChangeEvent)
            BindingContext lBindingContext = BindingContext.getCurrent();
            BindingContainer lBindingContainer = lBindingContext.getCurrentBindingsEntry();
            JUCtrlListBinding list = (JUCtrlListBinding) lBindingContainer.get("Status");
            int newindex = (Integer) valueChangeEvent.getNewValue();
            Object row = list.getDisplayData(); // Wichtig um die liste zu laden!!!!
            Row lFromList = (Row) list.getValueFromList(newindex);
            Object lAttribute = lFromList.getAttribute("Value");
            String newVal = (String) lAttribute;
        }to get the value from a selectOneChoice component...
    Timo

  • How to get the value of String in integer type

    how to get the value of String in integer

    {color:#0000ff}http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
    http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#valueOf(java.lang.String){color}

  • How to get the length of apex_item in javascript?

    Hello all
    I am having a tabular report using apex_item, I want to know how can i get the length of the item in javascript? like we do in pl/sql using apex_application.g_f01.count().
    and one more thing, when I go to certain page, tab of that page is getting disabled, what should I do to make tab available always whether I am on that page or on any other page.
    Thanks
    Tauceef

    Hi Oli
    Thanks for replying, In my first question actually I am validating the report values in javascript for that I need the length of the apex_item to run the loop that many times.
    Like we can get the length using apex_application.g_f011.count in pl/sql process how to get the length in the javascript, is there a way for that?
    I got the answer for the second question, this is the one.
    Thanks
    Tauceef

  • How to get the postion of any string

    hi
    like untitle.txt
    how to get the postion of '.'.
    Amit

    Hi Amit,
    Use SEARCH statement to find out a character or a string in a string.
    DATA V_STRING TYPE STRING VALUE 'untitle.txt'.
    SEARCH '.' FOR V_STRING.
    If search is successful then it will return position of character or string into system field SY-FDPOS.
    If your idea is get values of filename and extension by separating period then use simply SPLIT statement.
    SPLIT V_STRING AT '.' INTO V_FILE V_EXT .
    Thanks,
    Vinay
    Edited by: Vinaykumar G on Jul 1, 2008 8:52 PM

  • How to get the byte[] size dynamically from the StreamMessage object

    Hi all,
    Using JMS, I am receiving the FDF file as StreamMessage from the queue and attaching it to the PDF file which is present in the local system.
    For that, I have written the code as follows:
    {color:#0000ff} Message msg = jmsTemplate.receive();
    if(msg !=null && msg instanceof StreamMessage)
    StreamMessage message = (StreamMessage) msg;{color}
    {color:#ff6600}//hardcoded the byte array size value
    {color}{color:#0000ff} byte[] bytes = new byte[{color:#ff0000}856{color}];
    System.out.println("read msg="+message.readBytes(bytes));{color}
    {color:#0000ff}PdfReader pdfreader = new PdfReader("D:\\Managing_Workflows_No_Comment.pdf");
    PdfStamper stamp = new PdfStamper(pdfreader, new FileOutputStream("D:\\12345.pdf"));
    FdfReader fdfreader = new FdfReader(bytes);
    stamp.addComments(fdfreader);
    {color} {color:#0000ff} stamp.close();
    {color}{color:#000000}The above code is working fine except with the hardcoded of {color:#ff0000}byte array{color}{color:#ff0000} size value{color} which is given in {color:#ff0000}RED{color} in color.
    Can anybody know, {color:#000000}*how to get the byte[] size dynamically from the StreamMessage*{color} object ?
    Any help would be highly beneficial for me !!!!
    Thanks and Regards,
    Ganesh Kumar{color}

    When you create your stream message you could add an property to your message, something like streamSize that would contain the number of bytes in your stream message. Then you could get this property from the message before declaring your array.
    Tom

  • Just comparing one string how to get the node?

    hi group,
    I get the string value like this:
    String listselvalue = getJList1().getSelectedValue().toString();
    Just i am comparing this with particular node.(which is in tree) like this:
    TreePath path = getmy_tree().getPathForRow(1);
    DefaultMutableTreeNode selnode = (DefaultMutableTreeNode)path.getLastPathComponent();
    Enumeration enum = selnode.children();
    while(enum.hasMoreElements())
         if(enum.nextElement().toString().equalsIgnoreCase(listselvalue))
              //here what trick I have to use to get that node.(if it matches)
    thank u...
    Shalinipriya.

    You need your node for both your test and your manipulation if the test is succesfull, so just keep a ref to your node before the test, and use that ref for both test and manipulation. Within your code, it should look like this:
    Enumeration elts = selnode.children();
    while ( elts.hasMoreElements() ) {
         // keep a ref to the current node,
         // so you can bith test its name
         // and manipulate it if it match you critiria
         Object currentNode = elts.nextElement();
         if ( currentNode.toString().equalsIgnoreCase( listValue ) ) {
              // here you have your currentNode object
              // that is a DefaultMutableTreeNode
              doNodeJob( currentNode );
    }

Maybe you are looking for

  • How to know VAT cleared documents?

    HI, After receiving AR/AP for that period, I will clear VAT for some documents for that month, then how to know that which documents are VAT cleared and which are yet to be cleared. I want to create a report for the above requirement. So in which tab

  • Stuttering itunes

    I have been experiencing a stuttering effect with 7.1.1.5. The stuttering is a process, usually at the beginning of a new song, that causes the song to skip/pause for a second or two, then continue. This occurs about 4 times on average in a song to b

  • Domino Notes / Ldap connection Wls6.1

    hi all, is there a way to connect Wls 6.1 sp1 with Domino Notes 5 Ldap Server ? Can we do an authentification login for groups and user? If you did it can you reply me with a sample of connection parameters. thanks Hugues Simonnet Consultant Principa

  • Using StrobeMediaPlayback inside a Flash application?

    hi all -  i've got this to a point where i feel like i'm banging my head against the wall. i used this thread as a guide and it got me further along than all my previous attempts: http://forums.adobe.com/thread/702338 HOWEVER, i still can't get it wo

  • Zen touch, crashing with Windows XP professional, not working with Windows media pla

    i will start with an apology if someone has posted this up before i have just had a quick look and could not see any think about this. if i turn my computer on with out running any other programs and connect the zen touch the computer automatically t